import { generateID } from '../common/domutil'
export function convert(jsonSchema) {
    let json = optionsConvert(jsonSchema)
    json.column = toggleConvet(jsonSchema.components)
    return json
}

function toggleConvet(comps) {
    let arr = []
    comps.map(o => {
        switch(o.type) {
            case 'text':
                arr.push(baseConvert(o))
                break
            case 'button':
                arr.push(buttonConvert(o))
                break
            case 'number':
                arr.push(numberConvert(o))
                break
            case 'date':
                arr.push(dateConvert(o))
                break
            case 'table':
                arr.push(tableConvert(o))
                break
            default:
                console.log(`未能识别的组件类型：${o.type}`)
                break
        }
    })
    return arr
}

function optionsConvert(jsonSchema) {
    let json = Object.assign({
        labelPosition: 'right',
        labelSuffix: '',
        labelWidth: 120,
        gutter: 0,
        menuBtn: false,
        submitBtn: false,
        submitSize: "medium",
        submitText: "提交",
        emptyBtn: false,
        emptySize: "medium",
        emptyText: "清空",
        menuPosition: "center",
        tabs: false,
        detail: false,
        readonly: false,
        disabled: false
    }, jsonSchema)
    delete json.components
    return json
}

function baseConvert(schema) {
    return {
        type: schema.type,
        label: schema.label,
        span: parseInt(schema.span) || 24,
        display: true,
        size: "small",
        value: schema.value,
        width: schema.width,
        placeholder: schema.prop,
        controlsPosition: schema.labelPosition,
        prop: schema.id || schema.type + '_' + generateID(8)
    }
}

function buttonConvert(json) {
    return Object.assign(baseConvert(json), {
        component: 'el-button',
        type: json.btnType
    })
}

function dateConvert(json) {
    return Object.assign(baseConvert(json), {
        format: json.defaultFormat || "yyyy-MM-dd",
        valueFormat: json.defaultFormat || "yyyy-MM-dd"
    })
}

function numberConvert(json) {
    return Object.assign(baseConvert(json), {
        minRows: json.min,
        maxRows: json.max,
        step: json.step || 1
    })
}

function tableConvert(json) {
    let tableJson = Object.assign(baseConvert(json), {
        type: 'dynamic',
        children: {
            align: 'center',
            headerAlign: 'center',
            addBtn: true,
            delBtn: true
        }
    })
    let columns = []
    json.columns.map(c => {
        columns = columns.concat(toggleConvet(c.children))
    })
    tableJson.children.column = columns
    return tableJson
}